<script>
export default {
  callback: null,
  wxPlus: null,
  apiKey: 'wxfb65d9cea6d95d41',
  apiSecret: 'a521bddca0a930c250b18c5fb8390f3d',
  // 获取授权
  getCode: function (callback) {
    let $this = this
    $this.callback = callback
    var wxPlus = api.require('wxPlus')
    if (!wxPlus || !wxPlus.auth) {
      return alert('wxPlus不存在')
    }
    wxPlus.auth({
      apiKey: 'wxfb65d9cea6d95d41'
    }, function (ret, err) {
      if (ret.status) {
        $this.getToken(ret.code)
      } else {
        api.toast({msg: '微信授权失败-1,请稍后重试'})
      }
    })
  },
  // 获取置换accessToken
  getToken (code) {
    let $this = this
    var wxPlus = api.require('wxPlus')
    wxPlus.getToken({
      apiKey: this.apiKey,
      apiSecret: this.apiSecret,
      code: code
    }, function (ret, err) {
      if (ret.status) {
        // alert(JSON.stringify(ret));
        // ret.accessToken
        $this.getUserInfo(ret.accessToken, ret.openId)
      } else {
        // alert(err.code);
        api.toast({msg: '微信授权失败-2,请稍后重试'})
      }
    })
  },
  // 获取个人信息
  getUserInfo (accessToken, openId) {
    let $this = this
    var wxPlus = api.require('wxPlus')
    wxPlus.getUserInfo({
      accessToken: accessToken,
      openId: openId
    }, function (ret, err) {
      if (ret.status) {
        console.log('用户信息: ', JSON.stringify(ret))
        // alert(JSON.stringify(ret));
        if (typeof $this.callback === 'function') {
          $this.callback(ret)
        }
      } else {
        api.toast({msg: '微信授权失败-2,请稍后重试'})
      }
    })
  }
}
</script>

<style scoped>

</style>
